<template>
  <div class="dashboard-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>文件类型分布</span>
        </div>
      </template>
      
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import { getProjectFileStats } from '@/api/project'
import { mockFileStats } from '@/api/mock/projectMock'

const chartRef = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  chartInstance = echarts.init(chartRef.value)
  updateChart()
}

// 更新图表数据
const updateChart = async () => {
  if (import.meta.env.DEV) {
    chartInstance.setOption(getChartOption(mockFileStats))
    return
  }

  try {
    const res = await getProjectFileStats()
    const option = getChartOption(res.data)
    chartInstance.setOption(option)
  } catch (error) {
    console.error('获取文件统计失败:', error)
    // 开发环境下使用Mock数据
    if (import.meta.env.DEV) {
      chartInstance.setOption(getChartOption(mockFileStats))
    }
  }
}

// 获取图表配置
const getChartOption = (data) => {
  return {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '文件类型',
        type: 'pie',
        radius: '50%',
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

onMounted(() => {
  console.log('Dashboard组件已加载')
  initChart()
})

// 添加窗口大小变化监听
window.addEventListener('resize', () => {
  if (chartInstance) {
    console.log('窗口大小变化，重新调整图表')
    chartInstance.resize()
  }
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}
.card-header {
  font-size: 18px;
  font-weight: bold;
}
</style>
